import { Flex, Form, Input, Select ,  Button, Table, Space, Modal, Radio, message} from 'antd';
import style from '../css/Parameterconfiguration.module.scss'
import { SearchOutlined , PlusCircleOutlined} from '@ant-design/icons'
import type { RadioChangeEvent, TableProps ,  } from 'antd';
import { useEffect, useState } from 'react';
import { parameterdel, parameterinsert, parameterlists, parameterlistsID, parameterserch, parameterupdate } from '../utils/request';
import Padination from '../components/Pagination';
import moment from 'moment';
function Parameterconfiguration() {
    const [form] = Form.useForm();
    const [formOne] = Form.useForm();
    // 表格数据
    interface DataType {
        parameter_id: number;
        parametercode:string;
        Parameter:string;
        ParameterDescription:string;
        Parametervalues:Number;
        status:string;
        Attributionsystemcode:string;
        founder:string;
        createtime:string;
        ModifiedBy:string;
        last_modified:String
      }
      
      const columns: TableProps<DataType>['columns'] = [
        {
          title: '参数编码',
          dataIndex: 'parametercode',
          key: 'parametercode',
          width:144,
        },
        {
          title: '参数名称',
          dataIndex: 'Parameter',
          key: 'Parameter',
          width:145
        },
        {
          title: '参数说明',
          dataIndex: 'ParameterDescription',
          key: 'ParameterDescription',
          width:287,
          render:(text)=><p style={{width:'287px',whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}>{text}</p>
        },
        {
            title: '参数值',
            dataIndex: 'Parametervalues',
            key: 'Parametervalues',
            width:107,
            render:(text)=><p style={{width:'107px',whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}>{text}</p>
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width:89,
            render:(text)=>(text=='启用'?
                <span style={{color:'#00A76F'}}>{text}</span>
                :
                <span style={{color:'#EC2121'}}>{text}</span>
            )
          },
          {
            title: '归属系统编码',
            dataIndex: 'Attributionsystemcode',
            key: 'Attributionsystemcode',
            width:128
          },
          {
            title: '创建人',
            dataIndex: 'founder',
            key: 'founder',
            width:104,
          },
          {
            title: '创建时间',
            dataIndex: 'createtime',
            key: 'createtime',
            width:167,
            render:(text) =><span>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</span>,
          },
          {
            title: '修改人',
            dataIndex: 'ModifiedBy',
            key: 'ModifiedBy',
            width:104,
          },
          {
            title: '最后修改时间',
            dataIndex: 'last_modified',
            key: 'last_modified',
            width:167,
            render:(text) =><span>{text?moment(text).format("YYYY-MM-DD HH:mm:ss"):''}</span>,
          },
          {
            title: '操作',
            key: 'action',
            dataIndex: 'action',
            width:111,
            fixed: 'right',
            render: (_, record) => (
                <Space size="middle">
                    <a style={{color:'#0468FF'}} onClick={()=>edit(record.parameter_id)}>编辑</a>
                    <a style={{color:'#0468FF'}} onClick={()=>del(record.parameter_id)}>删除</a>
                </Space>
            ),
          },
      ];
      const [mockData,setMockData] = useState([])
      const [data,setData] = useState<DataType[]>([])
    
    useEffect(()=>{
        parameterlists().then(res=>{
            setMockData(res.data)
            setData(res.data.slice(0,10))
        }).catch(err=>{
            console.log(err)
        })
    },[])
    const [page,setPage] = useState({
        current:1,
        pageSize:10
    })
    const getshowsize = (data: any) => {
        setPage(data)
        setData(mockData.slice((data.current-1)*data.pageSize,data.pageSize*data.current))
    }
    // 重置
    const reset=()=>{
        console.log('重置')
        parameterlists().then(res=>{
            setMockData(res.data)
            setData(res.data.slice(0,10))
            form.resetFields()
        }).catch(err=>{
            console.log(err)
        })
    }
    // 搜索
    const serch=()=>{
        console.log('搜索')
        form.validateFields().then(values => {
            parameterserch(values).then(res=>{
                console.log(res.data)
                setMockData(res.data)
                setData(res.data.slice((page.current-1)*page.pageSize,page.pageSize*page.current))
            }).catch(err=>{
                console.log(err)
            })
        }).catch(info => {
            console.log('Validate Failed:', info);
        });
    }
    // 新建对话框单选
    const [value,setValue] = useState('启用')
    const Changeval=(e: RadioChangeEvent)=>{
        console.log('radio checked', e.target.value);
        setValue(e.target.value);
    }
    // 新建
    const [insertshow,setInsertshow] = useState(false)
    const [insertloading,setInsertloading] = useState(false)
    const [modal,setMadal] = useState('')
    const insert=()=>{
        setInsertshow(true)
        setMadal('新建')
    }
    // 编辑
    const edit=(i: number)=>{
        setMadal('编辑')
        setDleId(i)
        setInsertshow(true)
        parameterlistsID({
            id:i
        }).then(res=>{
            formOne.setFieldsValue(res.data[0])
        }).catch(err=>{
            console.log(err)
        })
    }
    // 删除
    const [delloading,setDelloading] = useState(false)
    const [delshow,setDelshow] = useState(false)
    const [delId,setDleId] = useState(0)
    const del=(i: any)=>{
        setDelshow(true)
        setDleId(i)
    }
    // 确认删除
    const confirmOk=()=>{
        setDelloading(true)
        setTimeout(() => {
            parameterdel({
                id:delId
            }).then(res=>{
                setDelloading(false)
                setDelshow(false)
                setMockData(res.data)
                setData(res.data.slice((page.current-1)*page.pageSize,page.pageSize*page.current))
                message.success(`删除操作成功！`);
            }).catch(err=>{
                console.log(err)
            })
            
        }, 2000);
    }
    // 取消删除
    const confirmCancel=()=>{
        console.log('取消删除')
        message.warning(`已取消操作！`);
        setDelshow(false)
    }
    // 新建取消
    const insertCancel=()=>{
        console.log('取消')
        formOne.resetFields()
        setInsertshow(false)
    }
    // 新建确定
    const insertOk=()=>{
        console.log('新建确定')
        setInsertloading(true)
        setTimeout(() => {
            formOne.validateFields().then(values => {
                console.log('Validated values: ', values);
                if(modal=='新建'){
                    parameterinsert(values).then(res=>{
                        setMockData(res.data)
                        setData(res.data.slice(0,10))
                        setInsertshow(false)
                        setInsertloading(false)
                        message.success('数据添加成功')
                    }).catch(err=>{
                        console.log(err)
                    })
                }else{
                    parameterupdate({
                        ...values,
                        id:delId
                    }).then(res=>{
                        console.log(res)
                        setMockData(res.data)
                        setData(res.data.slice(0,10))
                        setInsertshow(false)
                        setInsertloading(false)
                    }).catch(err=>{
                        console.log(err)
                    })
                }
                
            }).catch(info => {
                console.log('Validate Failed:', info);
            });
        }, 2000);
    }
    return ( 
        <>
            {/* 新建参数对话框 */}
            <Modal
                title='新建参数'
                open={insertshow}
                width={365}
                style={{marginTop:20}}
                onCancel={insertCancel}
                footer={[
                    <Flex key='flex' justify='flex-end'>
                        <Button key="back" onClick={insertCancel} style={{ height: 32, marginRight: 10 }}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={insertloading} onClick={insertOk} style={{ height: 32 }}>
                            确认
                        </Button>,
                    </Flex>
                ]}
            >
                <Form
                    form={formOne}
                    initialValues={{status:value}}
                >
                    <Form.Item label='参数编码' name='parametercode' rules={[{required:true}]} className={style.itemstyle}>
                        <Input placeholder='请输入'  style={{width:241,height:32,borderRadius:0}}></Input>
                    </Form.Item>
                    <Form.Item label='参数名称' name='Parameter' rules={[{required:true}]} className={style.itemstyle}>
                        <Input placeholder='请输入'  style={{width:241,height:32,borderRadius:0}}></Input>
                    </Form.Item>
                    <Form.Item label='参数值' name='Parametervalues' rules={[{required:true}]} className={style.itemstyle}>
                        <Input placeholder='请输入'  style={{width:241,height:32,borderRadius:0}}></Input>
                    </Form.Item>
                    <Form.Item label='状态' name='status'  className={style.itemstyle}>
                        <Radio.Group onChange={Changeval}>
                            <Radio value={'启用'}>启用</Radio>
                            <Radio value={'禁用'}>禁用</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item label='参数说明' name='ParameterDescription' rules={[{
                        required:true
                    }]} className={style.itemstyle}>
                        <Input placeholder='请输入'  style={{width:241,height:32,borderRadius:0}}></Input>
                    </Form.Item>
                </Form>
            </Modal>
            {/* 删除对话框 */}
            <Modal
                title={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E5%8F%82%E6%95%B0%E9%85%8D%E7%BD%AE/u10369.svg" alt="" />
                        <span style={{ marginLeft: 5 }}>删除确认</span>
                    </div>
                }
                open={delshow}
                onOk={confirmOk} 
                onCancel={confirmCancel}
                footer={[
                    <Flex key='flex' justify='flex-end'>
                        <Button key="back" onClick={confirmCancel} style={{ height: 32, marginRight: 10 }}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={delloading} onClick={confirmOk} style={{ height: 32 }}>
                            确认
                        </Button>,
                    </Flex>
                ]}
            >
                <p className={style.confirm}>是否继续操作删除时段操作？</p>
            </Modal>
            <div className={style.searchboxs}>
                <Form
                    form={form}
                    style={{height:'100%',
                        display:'flex',
                        justifyContent:'space-between',
                        alignItems:'center'
                    }}
                    initialValues={{ status:'全部状态'}}
                >
                    <Flex align='center' style={{height:'100%'}}>
                        <Form.Item label='参数名称' rules={[{required:true}]} name='Parameter' className={style.itemstyle}>
                            <Input allowClear style={{width:200,height:32}} ></Input>
                        </Form.Item>
                        <Form.Item label='参数编码' rules={[{required:true}]} name='parametercode' className={style.itemstyle}>
                            <Input allowClear style={{width:200,height:32}} ></Input>
                        </Form.Item>
                        <Form.Item label='全部状态' rules={[{required:true}]} name='status' className={style.itemstyle}>
                            <Select allowClear style={{width:200,height:32}}
                                options={[
                                    { value: '全部状态', label: '全部状态' },
                                    { value: '启用', label: '启用' },
                                    { value: '禁用', label: '禁用' },
                                ]}
                            ></Select>
                        </Form.Item>
                    </Flex>
                    <Flex>
                        <Button onClick={()=>reset()} style={{
                            width:60,
                            height:32,
                            marginRight:20,
                            borderRadius:0
                        }}>重置</Button>
                        <Button onClick={()=>serch()} style={{
                            width:75,
                            height:32,
                            backgroundColor:'#0460ff',
                            borderRadius:0
                        }} type="primary" icon={<SearchOutlined />}>
                            搜索
                        </Button>
                    </Flex>
                </Form>
            </div>
            <div className={style.datalists}>
                <Flex justify='flex-end'>
                    <Button onClick={()=>insert()} className={style.insertButton} type="primary" icon={<PlusCircleOutlined />} >新建参数</Button>
                </Flex>
                <Table rowKey='parameter_id' className={style.custom_table} columns={columns} dataSource={data} 
                scroll={{ x: 'max-content' }}
                pagination={false}
                ></Table>
                {/* 分页器 */}
                <Padination total={mockData.length} showsize={getshowsize}></Padination>
            </div>
        </>
     );
}

export default Parameterconfiguration;